﻿using System.Xml.Linq;
using FreeGoo.GameEngine.Renderables;
using FreeGoo.GameEngine.Renderables.Links;
using FreeGoo.GameEngine.Renderables.Particles;

namespace FreeGoo.LevelClasses.LevelParts
{
    public class LinkLevelPart : RenderableLevelPart
    {
        public override string Name { get { return "Link"; } }
        public override Renderable BuildRenderable(Level level, XElement element)
        {
            Particle linkFrom = level.Engine.GetRenderableById(element.Attribute("LinkFromId").Value) as Particle;
            Particle linkTo = level.Engine.GetRenderableById(element.Attribute("LinkToId").Value) as Particle;

            Link link = linkFrom.CreateLinkTo(linkTo);

            if (element.HasAttribute("Breakpoint"))
            {
                link.Joint.Breakpoint = element.Attribute("Breakpoint").ToFloat(link.Joint.Breakpoint);
            }
            else if (element.HasAttribute("BreakpointRelative"))
            {
                link.Joint.Breakpoint =
                    element.Attribute("BreakpointRelative").ToFloat(100) / 100.0f * link.TargetDistance;
            }

            if (element.HasAttribute("TargetDistance"))
            {
                link.TargetDistance = element.Attribute("TargetDistance").ToFloat(link.TargetDistance);
            }
            else if (element.HasAttribute("TargetDistanceRelative"))
            {
                link.TargetDistance =
                    element.Attribute("TargetDistanceRelative").ToFloat(100) / 100.0f * link.TargetDistance;
            }

            link.WantedTargetDistance = link.TargetDistance;
            return link;
        }
    }
}
